package com.sg.service.base.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sg.common.dto.FieldInfo;
import com.sg.common.exception.BizException;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.base.finance.req.*;
import com.sg.entity.OmsAccount;
import com.sg.mapper.OmsAccountMapper;
import com.sg.service.base.finance.MOmsAccountService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ：
 * @version 1.0
 * @since 2022/1/19 15:39
 */
@Service
public class MOmsAccountServiceImpl
        extends ServiceImpl<OmsAccountMapper, OmsAccount>
        implements MOmsAccountService {

    @Autowired
    OmsAccountMapper omsAccountMapper;

    /**
     * 7-1-01-批量查询财务账户列表ByIds[7672]
     * gen by moon at 2/19/2024, 2:53:25 PM
     */
    @Trace(operationName = "7-1-01-批量查询财务账户列表ByIds")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OmsAccount> batchQueryFinanceAccountListByIds(BatchQueryFinanceAccountListByIdsReq reqDto) {

        try {
            QueryWrapper<OmsAccount> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");
            reqDto.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
            if (reqDto.getFinanceAccountList() == null || reqDto.getFinanceAccountList().isEmpty()) {
                return new ArrayList<>();
            }
            queryWrapper.in("account_object_id", reqDto.getFinanceAccountList());
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(OmsAccount.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);

            return ((List<OmsAccount>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 7-1-01-查询资金账户详情[7677]
     * gen by moon at 11/4/2023, 11:54:15 PM
     */
    @Trace(operationName = "7-1-01-查询资金账户详情")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OmsAccount queryFinanceAccountDetailCom(QueryFinanceAccountDetailComReq reqDto) {

        try {
            reqDto.setIsValid("FALSE");
            QueryWrapper<OmsAccount> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<OmsAccount> retList = super.list(queryWrapper);
            if (retList != null && retList.size() > 0) {
                OmsAccount retData = retList.get(0);

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 7-1-01-新增资金账户[7679]
     * gen by moon at 11/25/2023, 5:34:31 PM
     */
    @Trace(operationName = "7-1-01-新增资金账户")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addFinanceAccount(OmsAccount omsAccount) {
        omsAccount.setAccountId(CommonFunctionHelper.getUid());//DISTRIBUTED_ID
        omsAccount.setAccountActualBalance(Double.valueOf("0"));//CUSTOM_CONVENTION
        omsAccount.setSettlableBalance(Double.valueOf("0"));//CUSTOM_CONVENTION
        omsAccount.setUnSettlableBalance(Double.valueOf("0"));//CUSTOM_CONVENTION
        omsAccount.setAccruedSettledAmount(Double.valueOf("0"));//CUSTOM_CONVENTION
        omsAccount.setTotalBudgetAmount(Double.valueOf("0"));//CUSTOM_CONVENTION
        omsAccount.setAccountStatus("NORMAL");
        omsAccount.setIsEndStatus("FALSE");
        omsAccount.setIsArchive("FALSE");
        omsAccount.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        omsAccount.setCreateInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        if (omsAccount != null && omsAccount.getSubjectLifeCycle() != null && omsAccount.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            omsAccount.setReleaseInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//RELEASED_CURRENT_INDUCTIONID
        }
        omsAccount.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        omsAccount.setCreateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        if (omsAccount != null && omsAccount.getSubjectLifeCycle() != null && omsAccount.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            omsAccount.setReleaseTime(CommonFunctionHelper.getCurrentTime());//RELEASE_SYSTEM_CURRENT_TIME
        }
        omsAccount.setIsValid("FALSE");
        if (super.save(omsAccount)) {
            return omsAccount.getAccountId();
        } else {
            return "-1";
        }

    }

    /**
     * 7-1-01-修改账户自动加[7688]
     * gen by moon at 11/7/2023, 1:13:13 PM
     */
    @Trace(operationName = "7-1-01-修改账户自动加")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAutoAddAccount(OmsAccount omsAccount) {
        // TODO: 2023/11/13 以下全部手写
        UpdateWrapper<OmsAccount> uw = new UpdateWrapper<>();
        uw.eq("account_id", omsAccount.getAccountId());
        if (omsAccount.getTotalBudgetAmount() != null) {
            uw.setSql("total_budget_amount = total_budget_amount + " + omsAccount.getTotalBudgetAmount());//ADD_NUMERICAL
        }
        if (omsAccount.getAccountActualBalance() != null) {
            uw.setSql("account_actual_balance = account_actual_balance + " + omsAccount.getAccountActualBalance());//ADD_NUMERICAL
        }
        if (omsAccount.getSettlableBalance() != null) {
            uw.setSql("settlable_balance = settlable_balance + " + omsAccount.getSettlableBalance());//ADD_NUMERICAL
        }
        if (omsAccount.getUnSettlableBalance() != null) {
            uw.setSql("un_settlable_balance = un_settlable_balance + " + omsAccount.getUnSettlableBalance());//ADD_NUMERICAL
        }
        if (omsAccount.getAccruedSettledAmount() != null) {
            uw.setSql("accrued_settled_amount = accrued_settled_amount + " + omsAccount.getAccruedSettledAmount());//ADD_NUMERICAL
        }


        omsAccount.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        omsAccount.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        omsAccount.setTotalBudgetAmount(null);
        omsAccount.setAccountActualBalance(null);
        omsAccount.setSettlableBalance(null);
        omsAccount.setUnSettlableBalance(null);
        omsAccount.setAccruedSettledAmount(null);
        return super.update(omsAccount, uw);

    }

    /**
     * 7-1-01-修改账户自动减[7689]
     * gen by moon at 11/4/2023, 11:54:16 PM
     */
    @Trace(operationName = "7-1-01-修改账户自动减")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAutoSubAccount(OmsAccount omsAccount) {
        omsAccount.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        omsAccount.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME

        UpdateWrapper<OmsAccount> uw = new UpdateWrapper<>();
        uw.eq("account_id", omsAccount.getAccountId());
        if (omsAccount.getTotalBudgetAmount() != null) {
            uw.setSql("total_budget_amount = total_budget_amount - " + omsAccount.getTotalBudgetAmount());//ADD_NUMERICAL
        }
        if (omsAccount.getAccountActualBalance() != null) {
            uw.setSql("account_actual_balance = account_actual_balance - " + omsAccount.getAccountActualBalance());//ADD_NUMERICAL
        }
        if (omsAccount.getSettlableBalance() != null) {
            uw.setSql("settlable_balance = settlable_balance - " + omsAccount.getSettlableBalance());//ADD_NUMERICAL
        }
        if (omsAccount.getAccruedSettledAmount() != null) {
            uw.setSql("accrued_settled_amount = accrued_settled_amount + " + omsAccount.getAccruedSettledAmount());//ADD_NUMERICAL
        }
        omsAccount.setTotalBudgetAmount(null);
        omsAccount.setAccountActualBalance(null);
        omsAccount.setSettlableBalance(null);
        omsAccount.setAccruedSettledAmount(null);
        return super.update(omsAccount, uw);
    }

    /**
     * 111117-1-01执行实体账户自动加[7695]
     * gen by moon at 11/7/2023, 1:13:14 PM
     */
    @Trace(operationName = "111117-1-01执行实体账户自动加")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean implementAutoAddEntityAccount(OmsAccount omsAccount) {
        UpdateWrapper<OmsAccount> uw = new UpdateWrapper<>();
        uw.eq("account_id", omsAccount.getAccountId());
        uw.setSql("total_budget_amount = total_budget_amount + " + omsAccount.getTotalBudgetAmount());//ADD_NUMERICAL
        uw.setSql("account_actual_balance = account_actual_balance + " + omsAccount.getAccountActualBalance());//ADD_NUMERICAL
        uw.setSql("settlable_balance = settlable_balance + " + omsAccount.getSettlableBalance());//ADD_NUMERICAL
        omsAccount.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        omsAccount.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        omsAccount.setTotalBudgetAmount(null);
        omsAccount.setAccountActualBalance(null);
        omsAccount.setSettlableBalance(null);
        return super.update(omsAccount, uw);

    }

    /**
     * 11117-1-01执行实体账户自动减[7696]
     * gen by moon at 11/4/2023, 11:54:17 PM
     */
    @Trace(operationName = "11117-1-01执行实体账户自动减")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean implementAutoSubEntityAccount(OmsAccount omsAccount) {
        UpdateWrapper<OmsAccount> uw = new UpdateWrapper<>();
        uw.eq("account_id", omsAccount.getAccountId());
        uw.setSql("accrued_settled_amount = accrued_settled_amount + " + omsAccount.getAccruedSettledAmount());//ADD_NUMERICAL
        omsAccount.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        omsAccount.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        omsAccount.setAccruedSettledAmount(null);
        return super.update(omsAccount, uw);

    }

    /**
     * 7-1-01修改资金账户[8368]
     * gen by moon at 2/2/2024, 7:53:17 PM
     */
    @Trace(operationName = "7-1-01修改资金账户")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFinanceAccount(OmsAccount omsAccount) {

        return super.updateById(omsAccount);
    }

    /**
     * 7-1-01查询资金账户列表[8419]
     * gen by moon at 2/4/2024, 2:02:47 AM
     */
    @Trace(operationName = "7-1-01查询资金账户列表")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OmsAccount> queryFinanceAccountList(QueryFinanceAccountListReq reqDto) {

        try {
            QueryWrapper<OmsAccount> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");

            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(OmsAccount.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);
            queryWrapper.orderByDesc("account_content_code");
            queryWrapper.orderByDesc("operate_time");
            return ((List<OmsAccount>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 7-1-01批量删资金账户[8512]
     * gen by moon at 2/18/2024, 10:07:18 PM
     */
    @Trace(operationName = "7-1-01批量删资金账户")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteFinanceAccount(List<String> reqDto) {

        if (reqDto == null || reqDto.size() == 0) {
            return false;
        }

        return super.removeByIds(reqDto);
    }

    /**
     * 7-1-01执行归属主体标识右模糊查账户[8518]
     * gen by moon at 2/19/2024, 7:43:23 PM
     */
    @Trace(operationName = "7-1-01执行归属主体标识右模糊查账户")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OmsAccount> implementContentCodeRightBlurQueryAccount(ImplementContentCodeRightBlurQueryAccountReq reqDto) {

        try {
            QueryWrapper<OmsAccount> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");

            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(OmsAccount.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);

            return ((List<OmsAccount>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 7-1-01批量查询财务账户byCode[7661]
     * gen by moon at 6/5/2024, 6:36:45 PM
     */
    @Trace(operationName = "7-1-01批量查询财务账户byCode")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OmsAccount> batchQueryFinanceAccount(BatchQueryFinanceAccountReq reqDto) {

        try {
            QueryWrapper<OmsAccount> queryWrapper = new QueryWrapper<>();

            if (reqDto.getAccountContentCodeList() == null || reqDto.getAccountContentCodeList().isEmpty()) {
                return new ArrayList<>();
            }
            queryWrapper.in("account_content_code", reqDto.getAccountContentCodeList());
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(OmsAccount.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(OmsAccount.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);
            queryWrapper.orderByDesc("account_content_code");
            queryWrapper.orderByDesc("operate_time");
            return ((List<OmsAccount>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 7-1-01批量改资金账户[9769]
     * gen by moon at 6/9/2024, 1:19:44 AM
     */
    @Trace(operationName = "7-1-01批量改资金账户")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateFinanceAccount(List<OmsAccount> omsAccount) {

        if (omsAccount == null || omsAccount.size() == 0) {
            return false;
        }
        return super.saveOrUpdateBatch(omsAccount);

    }
}
